package cn.itsource.ymcc.userdetails;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.mapper.PermissionMapper;
import cn.itsource.ymcc.result.JSONResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class JdbcUserDetailsService implements UserDetailsService {

    @Autowired
    private LoginMapper loginMapper ;

    @Autowired
    private PermissionMapper permissionMapper ;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.判断参数
        if(!StringUtils.hasLength(username)){
            throw new UsernameNotFoundException("用户不可为空");
        }

        //2.根据用户名查询User
        Login user =  loginMapper.selectByUsername(username);

        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //查询用户的权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(user.getId());

        List<SimpleGrantedAuthority>  authorities = new ArrayList<>();

        if(user.getType() == BaseConstants.Uaa.USER_TYPE_SYSTEM){
            authorities = permissions.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
        }

        //3.把User封装成UserDetails返回
        String password = user.getPassword() == null?"":user.getPassword();
        user.setPassword(null);
        return new org.springframework.security.core.userdetails.User(
                JSON.toJSONString(user),
                password,//密文
                user.getEnabled(),user.getAccountNonExpired(),user.getCredentialsNonExpired(),user.getAccountNonLocked(),
                authorities //用户的权限
        );
    }
}
